package com.sddr.register.nacos.operate;

import com.alibaba.cloud.nacos.NacosServiceInstance;
import com.sddr.base.frame.memory.ConfigMemory;
import com.sddr.base.frame.metadata.AbstractMetaDataOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.serviceregistry.Registration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 山顶洞人郑某
 * @className NacosMetaDataOperation.java nacos元数据操作实现
 * @date 2025 06 06
 */
public class NacosMetaDataOperation extends AbstractMetaDataOperation {

    public static final String SEPARATE = "@@";

    public NacosMetaDataOperation(Registration registration, ConfigMemory configMemory) {
        super(registration, configMemory);
    }

    /**
     * 获取元数据结果
     *
     * @param server 服务
     * @return 结果
     */
    @Override
    public Map<String, String> getMetadataFromServer(ServiceInstance server) {

        if ( server instanceof final NacosServiceInstance nacosServiceInstance) {
            return nacosServiceInstance.getMetadata();
        }

        return new HashMap<>(2);
    }


    @Override
    public String getServiceIdFromServer(ServiceInstance server) {
        String serviceId = super.getServiceIdFromServer(server);
        return getRelServiceId(serviceId);
    }

    @Override
    public String getServiceId() {
        String serviceId = super.getServiceId();
        return getRelServiceId(serviceId);
    }



    /**
     * 获取真实的服务ID
     * @param serviceId 原服务ID
     * @return 切割掉GROUP@@
     */
    private String getRelServiceId(String serviceId) {
        //Nacos注册中心会自动把服务名包装成GROUP@@服务名的格式，这里把GROUP@@去掉只留下服务名
        if (StringUtils.contains(serviceId, SEPARATE)) {
            serviceId = serviceId.substring(serviceId.indexOf(SEPARATE) + SEPARATE.length());
        }
        return serviceId;
    }
}
